package com.stn.zjx.givingtreasure.activity.askhelp;

import android.Manifest;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.came.viewbguilib.ButtonBgUi;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.web.GenericWebActivity;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.service.AmapLocationService;
import com.vondear.rxtools.RxActivityTool;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.HotCity;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;
import xyz.bboylin.universialtoast.UniversalToast;

public class AskLingHelpMapActivity extends BaseActivity implements AMap.OnMyLocationChangeListener, AMapLocationListener {


    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.city_location_tv)
    TextView cityLocationTv;
    @BindView(R.id.head)
    LinearLayout head;
    @BindView(R.id.go_need_bt)
    RelativeLayout goNeedBt;
    @BindView(R.id.location_bt)
    RelativeLayout locationBt;
    @BindView(R.id.go_detail_logo)
    RelativeLayout goDetailLogo;
    @BindView(R.id.go_detail_bt)
    ButtonBgUi goDetailBt;
    @BindView(R.id.go_tip_tv)
    TextView goTipTv;
    @BindView(R.id.go_tip_bt)
    RelativeLayout goTipBt;
    @BindView(R.id.go_list_bt)
    RelativeLayout goListBt;
    private AMap aMap = null;
    public boolean isFirst = true;
    public AmapLocationService amapLocationService;
     private String city="";
    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public void initComponent() {
        aMap = mapView.getMap();
        initMap();
    }

    //初始化地图
    private void initMap() {
        //移除高德地图图标
        aMap.getUiSettings().setLogoBottomMargin(-50);
        aMap.showIndoorMap(true);
        aMap.getUiSettings().setCompassEnabled(false);
        aMap.getUiSettings().setMyLocationButtonEnabled(false);
        aMap.getUiSettings().setScaleControlsEnabled(false);
        aMap.getUiSettings().setZoomControlsEnabled(false);
        MyLocationStyle style = new MyLocationStyle();
        style.radiusFillColor(getResources().getColor(R.color.transparent));
        style.strokeWidth(0.0F);
        style.strokeColor(getResources().getColor(R.color.transparent));
        style.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        style.interval(3000L);
        aMap.setMyLocationStyle(style);
        aMap.setMyLocationEnabled(true);
        aMap.setOnMyLocationChangeListener(this);
        aMap.setTrafficEnabled(false);
        aMap.setMapType(1);
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                return false;
            }
        });
        aMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:

                        head.setVisibility(View.GONE);
                        break;
                    case MotionEvent.ACTION_UP:

                        head.setVisibility(View.VISIBLE);
                        break;
                }
            }
        });

    }

    public void startLocation() {

        String[] perms = {
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_NETWORK_STATE
        };
        //是否有以上权限
        if (EasyPermissions.hasPermissions(this, perms)) {
            cityLocationTv.setText(getString(R.string.loading_location));
            this.amapLocationService = new AmapLocationService(this);
            this.amapLocationService.registerListener(this);
            this.amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
            this.amapLocationService.start();
        } else {
            cityLocationTv.setText(getString(R.string.error_location));
            //发起请求权限
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.request_perssion_desc),
                    REQUEST_PERMISSION, perms);
        }
    }

    public AMapLocationClientOption getDefaultAmapLocationOptions() {
        AMapLocationClientOption localAMapLocationClientOption = null;
        localAMapLocationClientOption = new AMapLocationClientOption();
        localAMapLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        localAMapLocationClientOption.setLocationCacheEnable(false);
        localAMapLocationClientOption.setOnceLocationLatest(false);
        localAMapLocationClientOption.setOnceLocation(true);
        localAMapLocationClientOption.setNeedAddress(true);
        localAMapLocationClientOption.setWifiScan(true);
        localAMapLocationClientOption.setInterval(1000);
        localAMapLocationClientOption.setHttpTimeOut(20000L);

        return localAMapLocationClientOption;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_asking_for_help_map);
        ButterKnife.bind(this);
        mapView.onCreate(savedInstanceState);
        initComponent();
        startLocation();
    }


    @Override
    public void onMyLocationChange(Location location) {
        System.out.println("***********" + location.getLatitude() + "*******" + location.getLongitude());
        System.out.println("****************onMyLocationChange*" + location.getProvider());
//        if (isFirst) {
//            aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
//            aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
//            isFirst = false;
//        }
    }


    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    protected void onSaveInstanceState(Bundle paramBundle) {
        super.onSaveInstanceState(paramBundle);
        mapView.onSaveInstanceState(paramBundle);
    }


    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        //      System.out.println("***********************onLocationChanged");

        if (aMapLocation != null) {
            city=aMapLocation.getCity();
            cityLocationTv.setText(city);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
            aMap.moveCamera(CameraUpdateFactory.zoomTo(15));


            LatLng marker1 = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            ArrayList<MarkerOptions> markers = new ArrayList<>();

            for (int i = 0; i < 1; i++) {
                MarkerOptions markerOptions = new MarkerOptions();
                //是否可以拖拽定位点
                markerOptions.draggable(true);
                LatLng latLng = new LatLng(aMapLocation.getLatitude() + (0.0001 + 0.0001 * i), aMapLocation.getLongitude() + (0.0001 + 0.0001 * i));
                //设置好坐标标题
                markerOptions.title("标题" + i);
                //设置定位点的显示效果
                markerOptions.setFlat(true);//设置marker平贴地图效果
                markerOptions.infoWindowEnable(false);
                markerOptions.setGps(false);

                markerOptions.position(latLng);
                markerOptions.icon(BitmapDescriptorFactory.fromView(View.inflate(AskLingHelpMapActivity.this, R.layout.amap_avatar, null)));

                markers.add(markerOptions);
            }
            ArrayList<Marker> markers1 = aMap.addMarkers(markers, true);
//              System.out.println("***********"+aMapLocation.getLatitude()+"*******"+aMapLocation.getLongitude());
//

        }else{
            city="";
            cityLocationTv.setText(getString(R.string.error_location));
        }
    }

    @OnClick({R.id.back_bt, R.id.head, R.id.go_need_bt, R.id.location_bt, R.id.go_detail_bt, R.id.go_tip_bt, R.id.go_list_bt,
    R.id.loading_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
            case R.id.head:

                break;

            case R.id.go_need_bt:
                RxActivityTool.skipActivity(this,ReleaseNeedHelpActivity.class);
                break;
            case R.id.location_bt:
                showToast1(getString(R.string.loading_location), UniversalToast.LENGTH_SHORT, 0, 0, 0);
                startLocation();
                break;
            case R.id.go_detail_bt:
                   Bundle bunble=new Bundle();
                   bunble.putString("url","http://help.jd.com/user/guide.html");
                RxActivityTool.skipActivity(this, GenericWebActivity.class,bunble);
                break;
            case R.id.go_tip_bt:
                break;
            case R.id.go_list_bt:
                break;
            case R.id.loading_bt:
                showCity();
                break;
        }
    }

    public void showCity(){
        List<HotCity> hotCities = new ArrayList<>();
        hotCities.add(new HotCity("北京", "北京", "101010100")); //code为城市代码
        hotCities.add(new HotCity("上海", "上海", "101020100"));
        hotCities.add(new HotCity("广州", "广东", "101280101"));
        hotCities.add(new HotCity("深圳", "广东", "101280601"));
        hotCities.add(new HotCity("杭州", "浙江", "101210101"));
      CityPicker cityPicker= CityPicker.from(this) //activity或者fragment
                .enableAnimation(true)	//启用动画效果，默认无
//                .setAnimationStyle(anim)	//自定义动画
                .setLocatedCity(null)
                .setHotCities(hotCities)	//指定热门城市
               ;
        cityPicker.setOnPickListener(new OnPickListener() {
            @Override
            public void onPick(int position, City data) {
                if(!data.getName().contains("市")){
                    city=data.getName()+"市";
                }
                cityLocationTv.setText(city);
            }

            @Override
            public void onLocate() {

                 AmapLocationService as=new AmapLocationService(AskLingHelpMapActivity.this);
                as.setmLocationOption(getDefaultAmapLocationOptions());
                as.registerListener(new AMapLocationListener() {
                    @Override
                    public void onLocationChanged(AMapLocation aMapLocation) {
                         if(aMapLocation!=null&&aMapLocation.getCity()!=null){
                             cityPicker.locateComplete(new LocatedCity(
                                     aMapLocation.getCity()
                                     .replace("市","")+"",
                                     aMapLocation.getProvince()
                                     .replace("省","")+ "",
                                     ""+aMapLocation.getCityCode()),LocateState.SUCCESS);
                         }else{
                             showToast1(getString(R.string.error_location), Gravity.CENTER,UniversalToast.LENGTH_SHORT,
                                     0,0);
                             cityPicker.locateComplete(null,LocateState.FAILURE);
                         }
                    }
                });
                as.start();
            }

            @Override
            public void onCancel() {

            }
        });
        cityPicker.show();
        //APP自身已定位的城市，传null会自动定位（默认）
    }
}
